package com.rickpan.controller;

import com.rickpan.common.Result;
import com.rickpan.service.TagService;
import com.rickpan.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 标签管理Controller
 *
 * @author RickPan Team
 * @since 2024-01-06
 */
@Slf4j
@RestController
@RequestMapping("/api/tags")
@Tag(name = "标签管理", description = "标签相关接口")
public class TagController {

    @Autowired
    private TagService tagService;

    /**
     * 获取标签列表
     */
    @GetMapping
    @Operation(summary = "获取标签列表", description = "获取指定类型的标签列表")
    public Result<List<com.rickpan.entity.Tag>> getTags(@RequestParam(required = false) String type,
                                                        @RequestParam(required = false) String search,
                                                        HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            List<com.rickpan.entity.Tag> tags;
            if (search != null && !search.trim().isEmpty()) {
                tags = tagService.searchTags(userId, search.trim());
            } else if (type != null && !type.trim().isEmpty()) {
                tags = tagService.getTagsByType(userId, type.trim());
            } else {
                tags = tagService.getAllTags(userId);
            }

            return Result.success(tags);
        } catch (Exception e) {
            log.error("获取标签列表失败", e);
            return Result.error("获取标签列表失败: " + e.getMessage());
        }
    }

    /**
     * 创建标签
     */
    @PostMapping
    @Operation(summary = "创建标签", description = "创建新的标签")
    public Result<com.rickpan.entity.Tag> createTag(@RequestBody Map<String, Object> request,
                                                   HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            String name = (String) request.get("name");
            String color = (String) request.get("color");
            String type = (String) request.get("type");

            if (name == null || name.trim().isEmpty()) {
                return Result.error("标签名称不能为空");
            }
            if (type == null || (!type.equals("file") && !type.equals("note"))) {
                return Result.error("标签类型必须是file或note");
            }

            com.rickpan.entity.Tag tag = tagService.createTag(userId, name.trim(), color, type);
            return Result.success("创建成功", tag);
        } catch (Exception e) {
            log.error("创建标签失败", e);
            return Result.error("创建标签失败: " + e.getMessage());
        }
    }

    /**
     * 更新标签
     */
    @PutMapping("/{tagId}")
    @Operation(summary = "更新标签", description = "更新标签信息")
    public Result<com.rickpan.entity.Tag> updateTag(@PathVariable Long tagId,
                                                   @RequestBody Map<String, Object> request,
                                                   HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            String name = (String) request.get("name");
            String color = (String) request.get("color");

            com.rickpan.entity.Tag tag = tagService.updateTag(tagId, userId, name, color);
            return Result.success("更新成功", tag);
        } catch (Exception e) {
            log.error("更新标签失败", e);
            return Result.error("更新标签失败: " + e.getMessage());
        }
    }

    /**
     * 删除标签
     */
    @DeleteMapping("/{tagId}")
    @Operation(summary = "删除标签", description = "删除指定标签")
    public Result<String> deleteTag(@PathVariable Long tagId,
                                   HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            boolean success = tagService.deleteTag(tagId, userId);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("标签不存在或无权删除");
            }
        } catch (Exception e) {
            log.error("删除标签失败", e);
            return Result.error("删除标签失败: " + e.getMessage());
        }
    }

    /**
     * 获取热门标签
     */
    @GetMapping("/popular")
    @Operation(summary = "获取热门标签", description = "获取使用频率高的标签")
    public Result<List<com.rickpan.entity.Tag>> getPopularTags(@RequestParam(required = false) String type,
                                                              @RequestParam(defaultValue = "10") Integer limit,
                                                              HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            List<com.rickpan.entity.Tag> tags = tagService.getPopularTags(userId);

            // 如果指定了类型，进行筛选
            if (type != null && !type.trim().isEmpty()) {
                tags = tags.stream()
                    .filter(tag -> type.equals(tag.getType()))
                    .limit(limit)
                    .collect(java.util.stream.Collectors.toList());
            } else {
                tags = tags.stream()
                    .limit(limit)
                    .collect(java.util.stream.Collectors.toList());
            }

            return Result.success(tags);
        } catch (Exception e) {
            log.error("获取热门标签失败", e);
            return Result.error("获取热门标签失败: " + e.getMessage());
        }
    }

    /**
     * 搜索标签
     */
    @GetMapping("/search")
    @Operation(summary = "搜索标签", description = "根据关键词搜索标签")
    public Result<List<com.rickpan.entity.Tag>> searchTags(@RequestParam String keyword,
                                                          @RequestParam(required = false) String type,
                                                          HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            List<com.rickpan.entity.Tag> tags = tagService.searchTags(userId, keyword);

            // 如果指定了类型，进行筛选
            if (type != null && !type.trim().isEmpty()) {
                tags = tags.stream()
                    .filter(tag -> type.equals(tag.getType()))
                    .collect(java.util.stream.Collectors.toList());
            }

            return Result.success(tags);
        } catch (Exception e) {
            log.error("搜索标签失败", e);
            return Result.error("搜索标签失败: " + e.getMessage());
        }
    }

    /**
     * 获取标签统计信息
     */
    @GetMapping("/stats")
    @Operation(summary = "获取标签统计信息", description = "获取标签的统计数据")
    public Result<Map<String, Object>> getTagStats(HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            TagService.TagStats tagStats = tagService.getTagStats(userId);

            Map<String, Object> result = new HashMap<>();
            result.put("totalTags", tagStats.getTotalTags());
            result.put("fileTags", tagStats.getFileTags());
            result.put("noteTags", tagStats.getNoteTags());

            return Result.success(result);
        } catch (Exception e) {
            log.error("获取标签统计信息失败", e);
            return Result.error("获取标签统计信息失败: " + e.getMessage());
        }
    }
}
